package com.easychat.service.impl;

import com.easychat.dto.TokenUserInfoDto;
import com.easychat.entity.UserContact;
import com.easychat.entity.query.UserContactQuery;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.enums.*;
import com.easychat.common.LeaseException;
import com.easychat.entity.UserInfo;
import com.easychat.entity.UserInfoBeauty;
import com.easychat.mappers.AccountMapper;
import com.easychat.mappers.UserContactDao;
import com.easychat.mappers.UserInfoBeautyDao;
import com.easychat.mappers.UserInfoDao;
import com.easychat.redis.RedisComponent;
import com.easychat.service.AccountService;
import com.easychat.service.UserContactService;
import com.easychat.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 10 2024/10/4
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserInfoBeautyDao userInfoBeautyDao;
    @Resource
    private AppConfig appConfig;
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private UserContactDao userContactDao;
    @Resource
    private UserContactService userContactService;


    /**
     * 注册
     * @param email
     * @param password
     * @param nickName
     */
    @Override
    @Transactional
    public void register(String email, String password, String nickName) {
        //查找email是否已经注册
        UserInfo userInfo = userInfoDao.queryByEmail(email);
        if(userInfo != null){
            //已经注册
            throw new LeaseException(ExceptionCodeEnum.ALREADY_REGIS);
        }
        String userId = StringTools.getUserId();
        UserInfoBeauty beautyAccount = userInfoBeautyDao.selectByEmail(email);
        Boolean noUserBeautyAccount = null != beautyAccount && BeautyAccountStatusEnum.NO_USE.getStatus().equals(beautyAccount.getStatus());
        if(noUserBeautyAccount){
            userId = UserContactTypeEnum.USER.getPrefix() + beautyAccount.getUserId();
            UserInfoBeauty userInfoBeauty = new UserInfoBeauty();
            userInfoBeauty.setStatus(BeautyAccountStatusEnum.USEED.getStatus());
            userInfoBeautyDao.update(userInfoBeauty);
        }
        Date date = new Date();
        userInfo = new UserInfo();
        userInfo.setEmail(email);
        userInfo.setUserId(userId);
        userInfo.setCreateTime(date);
        userInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
        userInfo.setPassword(StringTools.encodeMd5(password));
        userInfo.setLastOffTime(date.getTime());
        userInfo.setNickName(nickName);
        int insert = userInfoDao.insert(userInfo);
        if(insert == 0){
            throw new LeaseException(ExceptionCodeEnum.ERROR_LATER);
        }
        if(!noUserBeautyAccount){
            UserInfoBeauty updateBeauty = new UserInfoBeauty();
            updateBeauty.setStatus(BeautyAccountStatusEnum.USEED.getStatus());
            userInfoBeautyDao.updateById(updateBeauty,beautyAccount.getId());
        }
        //创建机器人好友
        userContactService.addContact4Robot(userId);

    }

    @Override
    public TokenUserInfoDto login(String email, String password) {
        UserInfo userInfo = userInfoDao.queryByEmail(email);
        if(userInfo == null){
            throw new LeaseException(ExceptionCodeEnum.USER_NOT_REGISTER);
        }
        if(StringTools.isEmpty(password) || !StringTools.encodeMd5(password).equals(userInfo.getPassword())){
            throw new LeaseException(ExceptionCodeEnum.PASSWORD_ERROR);
        }

        if(!(userInfo.getStatus().equals(UserStatusEnum.ENABLE.getStatus()))){
            throw new LeaseException(ExceptionCodeEnum.ACCOUNT_DISABLE);
        }
        //查询联系人
        UserContactQuery userContactQuery = new UserContactQuery();
        userContactQuery.setUserId(userInfo.getUserId());
        userContactQuery.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        List<UserContact> userContactList = userContactDao.selectList(userContactQuery);
        List<String> contactIdList = userContactList.stream().map(item -> item.getContactId()).collect(Collectors.toList());
        redisComponent.cleanUserContact(userInfo.getUserId());
        if(!contactIdList.isEmpty()){

            redisComponent.addUserContactBatch(userInfo.getUserId(),contactIdList);
        }

        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto(userInfo);

        Long userHeartBeat = redisComponent.getUserHeartBeat(userInfo.getUserId());
        if(userHeartBeat!=null){
            throw new LeaseException(ExceptionCodeEnum.ALREADY_LOGGED);
        }
        String token = StringTools.encodeMd5(tokenUserInfoDto.getUserId() + StringTools.getRandomString(Constants.RANDOM_20));
        tokenUserInfoDto.setToken(token);
        //存入token到redis中
        redisComponent.saveTokenUserInfoDto(tokenUserInfoDto);


        return tokenUserInfoDto;


    }

    private TokenUserInfoDto getTokenUserInfoDto(UserInfo userInfo){
        TokenUserInfoDto tokenUserInfoDto = new TokenUserInfoDto();
        tokenUserInfoDto.setUserId(userInfo.getUserId());
        tokenUserInfoDto.setNickName(userInfo.getNickName());

        String adminEmails = appConfig.getAdminEmail();
        //判断配置文件里配置的admin账号里是否有这个账号，因为以逗号分隔，所以split(",")
        if(!StringTools.isEmpty(adminEmails) && ArrayUtils.contains(adminEmails.split(","),userInfo.getEmail())){
            tokenUserInfoDto.setAdmin(true);
        }else {
            //TODO 查询稳定群组
            //TODO 查询我的联系人
            tokenUserInfoDto.setAdmin(false);
        }
        return tokenUserInfoDto;
    }
}

